<script setup lang="ts">
import CdlTable from "@/components/table";
import CdlSearch from "@/components/search";
import CdlForm from "@/components/form"
import CreateAndModifyDriver from "@/views/vehicleManage/driver/fleet/createAndModifyDriver.vue"
import {useTablePagingTemplate} from "@/hooks/TableHooks";
import {useRouter} from "vue-router";
import {reactive, h} from "vue";
import {createPopup} from "@/utils/createPopup";
import {useFormTemplate} from "@/hooks/formHooks";
import {useGetDriverListApi} from "@/api/vehicle/fleet";
import type {Fleet} from "@/interfaces/views/vehicle/driver";
import type {Mode, Query, State, FormData} from "@/interfaces/components/Page";
import type {FormTree} from "@/interfaces/components/Form";
import type {TableTree} from "@/interfaces/components/Table";

const router = useRouter()
const request = {
  createdIsNeed: true,
  url: "/slag-truck/fleet",
}
const state = reactive<State<Query<Fleet>, Fleet>>({
  queryForm: {},
  dataList: []
})
const {query, added, update, handleCurrentChange, handleSizeChange, loading} = useTablePagingTemplate(request, state)

const searTree: FormTree<Fleet> = [
    [
      {label: "车队名", component: "input", prop: "name"},
      {label: "车队队长", component: "input", prop: "captainName"},
    ]
]

const tree: TableTree<Fleet> = {
  colRule: [
    {ti: "车队名称", prop: "name"},
    {ti: "关联司机数", prop: "captainNumber"},
    {ti: "车队长", prop: "captainName"},
    {ti: "备注", prop: "remark"},
  ],
  control: [
    {name: "编辑", type: "success", method: openCreateFleetUpdate},
    {name: "添加司机", type: "primary", method: openFleetVehicleInsert},
    {name: "移除司机", type: "danger", method: openFleetVehicleDel},
  ]
}
const fleetFormTree: FormTree<Fleet> = [
    [
      {label: "车队名称", component: "input", prop: "name", rule: [
          { required: true, message: '必须填写车队名称', trigger: 'blur' },
          { max: 18, message: '车队名称最长18个字符', trigger: 'blur' }
        ]},
      {label: "车队长", component: "select", prop: "captainId", serviceOptionKey: "driverList",
        optionProps: { label: "name", value: "id"}, placeholder: "请选择车队队长", rule: [
          { required: true, message: '必须选择车队队长', trigger: 'change' }
        ]}
    ],
    [
      {label: "备注", component: "input", type: "textarea", prop: "remark"},
    ]
]
const fleetData: FormData<Fleet> = {
  name: "",
  captainId: undefined,
  remark: ""
}

/**
 * 打开车队新增
 */
function openCreateFleetInsert(){
  driverArr = []
  createPopup("新增车队", h(CdlForm, {
    templateTree: fleetFormTree,
    model: fleetData,
    init: {"driverList": getDriverList}
  }), "add", popupCallBack)
}

/**
 * 打开车队修改
 * @param data
 */
function openCreateFleetUpdate(data: Fleet){
  driverArr = [{id: data.captainId, name: data.captainName}]
  createPopup("修改车队", h(CdlForm, {
    templateTree: fleetFormTree,
    model: createPopupDataTemplate(data),
    init: {"driverList": getDriverList}
  }), "update", popupCallBack)
}

/**
 * 车队添加司机
 * @param data
 */
function openFleetVehicleInsert(data: Fleet){
  createPopup("添加司机", h(CreateAndModifyDriver, {
    id: data.id,
    name: data.name,
    query: query
  }))
}

/**
 * 车队删除司机
 * @param data
 */
function openFleetVehicleDel(data: Fleet){
  createPopup("删除司机", h(CreateAndModifyDriver, {
    id: data.id,
    query: query,
  }))
}
let driverArr: any[] = []
/**
 * 获取司机列表
 */
function getDriverList(){
  return new Promise((resolve) => {
    useGetDriverListApi().then(res => {
      driverArr.push(...res.data)
      resolve(driverArr)
    })
  })
}
/**
 * 回调处理
 * @param mode
 * @param data
 */
function popupCallBack(mode: Mode, data: any){
  switch (mode) {
    case "add":
      added(dataPreprocessing(data))
      break
    case "update":
      update(dataPreprocessing(data))
      break
  }
}

/**
 * 数据预处理
 * @param data
 */
function dataPreprocessing(data: Fleet) {
  for (let i = 0; i <driverArr.length; i++){
    if(driverArr[i].id === data.captainId){
      data.captainName = driverArr[i].name
    }
  }
  return data
}
const {createPopupDataTemplate} = useFormTemplate(fleetData)
</script>
<template>
  <el-card>
    <CdlSearch :model="state.queryForm" :template-tree="searTree">
      <template #menu>
        <el-button type="primary" @click="openCreateFleetInsert">添加</el-button>
      </template>
    </CdlSearch>
    <CdlTable :template-tree="tree" :data="state.dataList" :control-width="300" :loading="loading"></CdlTable>
    <el-pagination
        :current-page="state.page"
      :page-sizes="state.pageSizes!"
        :page-size="state.limit"
      :total="state.total"
      hide-on-single-page
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </el-card>
</template>
